package com.huitone.gddw.service.impl.monitoring;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

import com.huitone.gddw.common.excel.CreateExcel;
import com.huitone.gddw.dao.entity.AlarmReceiveUser;
import com.huitone.gddw.dao.entity.ClusterInfo;
import com.huitone.gddw.dao.entity.ObjItem;
import com.huitone.gddw.dao.entity.ObjItemProperty;
import com.huitone.gddw.dao.entity.ObjectManagement;
import com.huitone.gddw.dao.entity.RedisItem;
import com.huitone.gddw.dao.entity.ReturnedValue;
import com.huitone.gddw.dao.entity.Trigger;
import com.huitone.gddw.dao.monitoring.ObjectItemDao;
import com.huitone.gddw.service.RedisItemService;
import com.huitone.gddw.utils.MonitoringResult;
import com.huitone.gddw.utils.MonitoringUtils;
import com.huitone.gddw.utils.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 保存、查找redis监控数据service实现类
 * @author lipengfei
 *
 */
@Service("redisService")
public class RedisItemServiceImpl implements RedisItemService {
	
	private final static Logger LOGGER = Logger.getLogger(RedisItemServiceImpl.class);
	
	@Resource
	ObjectItemDao  objDao;
	@Override
	public MonitoringResult<Map<String, Object>> loadRedis(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
						
		//用于存放RedisItem对象的集合
		List<RedisItem> redisList = new ArrayList<RedisItem>();
		
		//用于存放返回数据的map
		Map<String, Object> redisMap= new HashMap<>();
		
		//传入页码，在数据库全部对象表中查找redis类型的数据
		Map<String, Object> map = MonitoringUtils.getMap(value.getPageNo(),value.getPageSize());
		map.put("objType", "redis");
		List<ObjectManagement> objList = objDao.selectObjAllByObjType(map);
		System.out.println(objList);
		
		if(!objList.isEmpty()){
			for(ObjectManagement obj:objList){
				Map<String, String> objmap = new HashMap<>();
				objmap.put("objId", obj.getObjId());
				objmap.put("itemName", "basic");
				ObjItem objitem = objDao.selectObjItemByItemName(objmap);
				if(objitem!=null){
					List<Map<String, String>> proList = objDao.selectValue(objitem.getItemId());
					RedisItem redisItem = new RedisItem();
					if(!proList.isEmpty()){
						for (Map<String, String> item:proList) {
							if(item.get("KEY").equals("ip")){
								redisItem.setRedisIP(item.get("VALUE"));
							}else if(item.get("KEY").equals("rltip")){
								redisItem.setRedisPrin(item.get("VALUE"));
							}else if(item.get("KEY").equals("links")){
								redisItem.setConnectCount(StringUtils.strToInteger(item.get("VALUE")));
							}else if(item.get("KEY").equals("linkuse")){
								redisItem.setConUseage(item.get("VALUE"));
							}else if(item.get("KEY").equals("allocmem")){
								redisItem.setUseMem(StringUtils.strToInteger(item.get("VALUE")));
							}else if(item.get("KEY").equals("mempiece")){
								redisItem.setMemUseage(item.get("VALUE"));
							}
						}
					}
					redisItem.setRedisName(obj.getObjName());
					redisItem.setRedisId(obj.getObjId());
					redisItem.setAlarmCount(objDao.getAllWarnCount(objmap));
					AlarmReceiveUser user = objDao.getAlarmReceiveUser(objmap);
					if(user!=null){
						redisItem.setPripacal(user.getReceiveUser());
						redisItem.setPhone(user.getPhone());
						redisItem.setEmail(user.getEmail());
					}
					redisList.add(redisItem);
					result.setMsg("查询redis信息成功");
					result.setStatus(0);
					
				}else{
					LOGGER.info("没有该redis的基本信息");
				}
			}
		}else{
			LOGGER.info("没有redis类型的对象数据");
		}
		
		List<RedisItem> allName = new ArrayList<RedisItem>();
		Map<String, String> allNameMap= new HashMap<>();
		allNameMap.put("objType", "redis");
		List<ObjectManagement> allNameList = objDao.selectObjName(allNameMap);
		if(!allNameList.isEmpty()){
			for(ObjectManagement obj:allNameList){
				RedisItem redisItem = new RedisItem();
				redisItem.setRedisName(obj.getObjName());
				redisItem.setRedisId(obj.getObjId());
				allName.add(redisItem);
			}
		}else{
			LOGGER.info("没有redis类型的对象数据");
		}
		
		map.put("objType", "redisclus");
		List<ObjectManagement> clusObjList = objDao.selectObjAllByObjType(map);
		ClusterInfo clusterInfo = new ClusterInfo();
		if(!clusObjList.isEmpty()){	
			for(ObjectManagement obj:clusObjList){
				Map<String, String> objmap = new HashMap<>();
				objmap.put("objId", obj.getObjId());
				objmap.put("itemName", "cluster");
				ObjItem item = objDao.selectObjItemByItemName(objmap);
				if(item !=null){
					List<Map<String, String>> clusterList= objDao.selectValue(item.getItemId());
					if(!clusterList.isEmpty()){
						for (Map<String, String> clu:clusterList) {
							if(clu.get("KEY").equals("parts")){
								clusterInfo.setParts(clu.get("VALUE"));
							}else if(clu.get("KEY").equals("nodes")){
								clusterInfo.setNodes(clu.get("VALUE"));
							}else if(clu.get("KEY").equals("allocslots")){
								clusterInfo.setAllocslots(clu.get("VALUE"));
							}else if(clu.get("KEY").equals("downslots")){
								clusterInfo.setDownslots(clu.get("VALUE"));
							}else if(clu.get("KEY").equals("status")){
								clusterInfo.setStatus(clu.get("VALUE"));
							}
						}
					}
				}else{
					LOGGER.info("没有redis集群信息");
				}
			}
		}else{
			LOGGER.info("没有redis集群信息对象");
		}
		result.setMsg("redis信息获取成功");
		result.setStatus(0);
		redisMap.put("cluster", clusterInfo);
		redisMap.put("redisList", redisList);
		redisMap.put("allnames", allNameList);	
		System.out.println(redisMap);
		//对数据结果进行包装传送
		result.setData(redisMap);
		result.setPageNo(value.getPageNo());
		result.setPageSize(value.getPageSize());
		result.setTotalCount(objDao.selectObjCountByType(map));
		return result;
	}
	@Override
	public MonitoringResult<Map<String, Object>> addIndex() {
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		
		Map<String, Object> resultMap = new HashMap<>();
		//存放节点主ip
		List<RedisItem> redisIpList = new ArrayList<RedisItem>(); 
		//参数
		Map<String, String> map = new HashMap<>();
		map.put("objType","redis");
		RedisItem redisItem = new RedisItem();
		List<ObjectManagement> objList = objDao.selectObjName(map);
		if(!objList.isEmpty()){
			List<AlarmReceiveUser> alarmUserList = objDao.selectAlarmReceiveUser(objList.get(0).getObjId());
			for(ObjectManagement obj:objList){
				map.put("objId", obj.getObjId());
				map.put("itemName", "basic");
				ObjItem objItem = objDao.selectObjItemByItemName(map);
				if(objItem !=null){
					List<Map<String, String>> proList = objDao.selectValue(objItem.getItemId());
					if(!proList.isEmpty()){	
						for (Map<String, String> item:proList) {
							if(item.get("KEY").equals("ip")){
								redisItem.setRedisIP(item.get("VALUE"));
							}
						}		
					}else{
						LOGGER.info("没有该redis的指标信息");
					}
				}
				redisItem.setRedisId(obj.getObjId());
				redisIpList.add(redisItem);
			}
				resultMap.put("redisIps", redisIpList);
				resultMap.put("alarmusers", alarmUserList);
				result.setStatus(0);
				result.setMsg("redisIp获取成功");
				result.setData(resultMap);
				return result;
		}else{
			LOGGER.info("没有redis监控对象");
		}
		result.setMsg("redisIp获取失败");
		return result;
		
	}
	@Override
	public MonitoringResult<Map<String, Object>> showIndex(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//用于存放结果数据
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//存放参数
		Map<String, String> map = new HashMap<>();
		map.put("objId", value.getHostId());
		map.put("itemName", "basic");
		//获取指标的名称和告警接受人
		List<ObjItemProperty> indexnamelist = new ArrayList<ObjItemProperty>();
		List<AlarmReceiveUser> alarmUserList = objDao.selectAlarmReceiveUser(value.getHostId());
		
		ObjItem objItem = objDao.selectObjItemByItemName(map);
		if(objItem !=null){
			List<ObjItemProperty> indexname = objDao.getIndexName(objItem.getItemId());
			if(!indexname.isEmpty()){
				indexnamelist.addAll(indexname);
				result.setStatus(0);
				result.setMsg("主机监控指标名称获取成功,告警接收人获取成功");
			}else{
				LOGGER.info("没有需要添加的redis监控指标");
			}
		}else{
			LOGGER.info("没有找到redis基本信息");
		}
		resultMap.put("indexnames", indexnamelist);
		resultMap.put("alarmusers", alarmUserList);
		result.setData(resultMap);
		return result;
	}

	@Override
	public MonitoringResult<RedisItem> save(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<RedisItem> result = new MonitoringResult<RedisItem>();
		try {
			if(value.getIndex()!=null && value.getAlarmRecUser()!=null){
				JSONArray indexja =JSONArray.fromObject(URLDecoder.decode(value.getIndex(),"UTF-8")); 
				JSONArray alarmja = JSONArray.fromObject(URLDecoder.decode(value.getAlarmRecUser(),"UTF-8"));
					for(int i = 0;i< indexja.size();i++){
						JSONObject indexjb = indexja.getJSONObject(i);
								if(!indexjb.getString("alarmLevel").isEmpty()){
									//保存指标信息
									ObjItemProperty objItemProperty = new ObjItemProperty();
									objItemProperty.setKeyNameCn(indexjb.getString("indexName"));
									objItemProperty.setKeyId(indexjb.getString("keyId"));
//									if(!indexjb.getString("quantity").isEmpty()){
//										objItemProperty.setQuantity(StringUtils.strToDouble(indexjb.getString("quantity")));
//									}
//									objItemProperty.setIndexUnit(indexjb.getString("unit"));
									objDao.updateIndex(objItemProperty);
									//保存告警信息
									Trigger trigger = new Trigger();
									String triggerId = StringUtils.uuid();
									trigger.setTriggerId(triggerId);
									trigger.setItemId(objDao.selectItemIdByKeyId(indexjb.getString("keyId")));
									trigger.setKeyId(indexjb.getString("keyId"));
									if(!indexjb.getString("upperLimit").isEmpty()){
										trigger.setUpperLimit(StringUtils.strToDouble(indexjb.getString("upperLimit")));
									}
									if(!indexjb.getString("lowerLimit").isEmpty()){
										trigger.setLowerLimit(StringUtils.strToDouble(indexjb.getString("lowerLimit")));
										
									}
//									trigger.setAlarmLevel(StringUtils.strToInteger(indexjb.getString("alarmLevel")));
//									trigger.setSustainTime(indexjb.getString("sustainTime"));
									trigger.setIndexDesc(indexjb.getString("indexDesc"));
									objDao.saveAlarm(trigger);
									//保存告警接受人
									for(int j = 0;j<alarmja.size();j++){
										JSONObject alarmjb = alarmja.getJSONObject(j);
										AlarmReceiveUser user = new AlarmReceiveUser();
										user.setRceId(alarmjb.getString("rceId"));
										user.setObjId(value.getHostId());
										user.setReceiveUser(alarmjb.getString("receiveUser"));
										user.setPhone(alarmjb.getString("phone"));
										user.setEmail(alarmjb.getString("email"));
										user.setUserType(alarmjb.getString("userType"));
										user.setRecAlarmLevel1(alarmjb.getString("recAlarmLevel1"));
										
										user.setRecAlarmLevel2(alarmjb.getString("recAlarmLevel2"));
										
										user.setRecAlarmLevel3(alarmjb.getString("recAlarmLevel3"));
										
										objDao.updateUser(user);
									}
									
							}else{
								result.setMsg("必须添加告警信息");
								return result;
							}
						}
					result.setStatus(0);
					result.setMsg("保存成功");
					return result;

				}else{
					result.setMsg("监控指标或接收人不能为空,保存失败");
				}
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("保存失败");
		}
		return result;
		
	}
//	@SuppressWarnings("null")
//	@Override
//	public MonitoringResult<Map<String, Object>> updata(ReturnedValue value) {
//		//用于传递数据结果的方法
//		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
//		//存放参数
//		Map<String, String> map = new HashMap<>();
//		map.put("objId", value.getHostId());
//		map.put("itemName", "basic");
//		//用于存储数据结果map
//		Map<String, Object> mainMap = new HashMap<>();
//		//存放指标的集合
//		List<Index> indexList = new ArrayList<Index>();
//		//存放告警接受人的集合
//		List<AlarmReceiveUser> userList =new ArrayList<AlarmReceiveUser>();
//		Index index = new Index();
//		ObjectManagement obj = objDao.selectObjById(map);
//		if(obj!=null){
//		ObjItem objItem = objDao.selectObjItemByItemName(map);
//		if(objItem !=null){
//						List<ObjItemProperty> objProperty = objDao.selectProperty(objItem.getItemId());
//						for(ObjItemProperty itemPro:objProperty){
//							map.put("itemId", objItem.getItemId());
//							map.put("keyId", itemPro.getKeyId());
//							Trigger trigger = objDao.selectAlarm(map);
//							
//								index.setIndexName(itemPro.getKeyName());
//								index.setQuantity(itemPro.getQuantity());
//								index.setUnit(itemPro.getIndexUnit());
//								index.setAlarmLevel(StringUtils.intToString(trigger.getAlarmLevel()));
//								index.setUpperLimit(trigger.getUpperLimit());
//								index.setLowerLimit(trigger.getLowerLimit());
//								index.setSustainTime(trigger.getSustainTime());
//								indexList.add(index);
//								List<AlarmReceiveUser> recList = objDao.selectAlarmReceiveUser(trigger.getTriggerId());
//								for(AlarmReceiveUser rec:recList){
//									if(userList!=null){
//										for(AlarmReceiveUser user:userList){
//											if(!(user.getRceId().equals(rec.getRceId()))){
//												userList.add(rec);
//											}
//										}
//									}else{
//										userList.add(rec);
//									}
//									
//									
//								}
//							
//							mainMap.put("index", indexList);
//							mainMap.put("receiver", userList);
//							result.setStatus(0);
//							result.setMsg("redis监控指标信息获取成功");
//							result.setData(mainMap);
//							return result;
//						}
//						
//					}else{
//						MonitoringUtils.MonitoringException("该redis还没添加指标监控");
//					}
//				}else{
//					MonitoringUtils.MonitoringException("该redis不存在");
//				}
//				mainMap.put("index", indexList);
//				mainMap.put("receiver", userList);
//				result.setData(mainMap);
//				return result;
//		
//	}

//	@Override
//	public MonitoringResult<List<RedisItem>> select(ReturnedValue value) {
//		MonitoringResult<List<RedisItem>> result = new MonitoringResult<List<RedisItem>>();
//		//用于存放RedisItem对象的集合
//		List<RedisItem> redisList = new ArrayList<RedisItem>();
//		Map<String, String> map = new HashMap<>();
//		map.put("objId", value.getHostId());
//		map.put("itemName", "basic");
//		ObjectManagement obj= objDao.selectObjById(map);
//		if(obj !=null){
//			ObjItem objitem = objDao.selectObjItemByItemName(map);
//			if(objitem!=null){
//				List<Map<String, String>> proList = objDao.selectValue(objitem.getItemId());
//				RedisItem redisItem = new RedisItem();
//				for (Map<String, String> item:proList) {
//					if(item!=null){
//						if(item.get("KEY").equals("role")){
//							redisItem.setRedisName(item.get("VALUE"));
//						}else if(item.get("KEY").equals("ip")){
//							redisItem.setRedisIP(item.get("VALUE"));
//						}else if(item.get("KEY").equals("rltip")){
//							redisItem.setRedisPrin(item.get("VALUE"));
//						}else if(item.get("KEY").equals("links")){
//							redisItem.setConnectCount(StringUtils.strToInteger(item.get("VALUE")));
//						}else if(item.get("KEY").equals("linkuse")){
//							redisItem.setConUseage(item.get("VALUE"));
//						}else if(item.get("KEY").equals("allocmem")){
//							redisItem.setUseMem(StringUtils.strToInteger(item.get("VALUE")));
//						}else if(item.get("KEY").equals("mempiece")){
//							redisItem.setMemUseage(item.get("VALUE"));
//						}
//						redisItem.setRedisIP(obj.getObjId());
//						redisItem.setAlarmCount(objDao.getAllExcptionCount(obj.getObjId()));
//						AlarmReceiveUser user = objDao.getAlarmReceiveUser(obj.getObjId());
//							if(user!=null){
//								redisItem.setPripacal(user.getReceiveUser());
//								redisItem.setPhone(user.getPhone());
//								redisItem.setEmail(user.getEmail());
//							}
//						redisList.add(redisItem);
//						result.setStatus(0);
//						result.setMsg("redis监控条件查询成功");
//					}else{
//						MonitoringUtils.MonitoringException("没有该redis的指标信息");
//					}
//				}
//			}else{
//				MonitoringUtils.MonitoringException("没有该redis的基本信息");
//			}
//		}else{
//			MonitoringUtils.MonitoringException("没有该redis类型的对象数据");
//		}
//		result.setData(redisList);
//		return result;
//	}
	@Override
	public MonitoringResult<List<Map<String,String>>> getAllInfo(ReturnedValue value) {
		// TODO Auto-generated method stub
		//用于传递数据结果的方法
		MonitoringResult<List<Map<String,String>>> result = new MonitoringResult<List<Map<String,String>>>();
		//存放参数
		Map<String, String> map = new HashMap<>();
		map.put("objId", value.getHostId());
		map.put("itemName", "basic");
		//用于存储数据结果map
		List<Map<String,String>> infoMap = new ArrayList<Map<String,String>>();
		ObjectManagement obj = objDao.selectObjById(value.getHostId());
		if(obj!=null){
		ObjItem objItem = objDao.selectObjItemByItemName(map);
		if(objItem !=null){
			List<Map<String,String>> infolist = objDao.selectCnValue(objItem.getItemId());	
			if(!infolist.isEmpty()){
				for(int i = 1;i<=Math.ceil(infolist.size()/3);i++){
					Map<String, String> valueMap = new HashMap<String, String>();
					for(int j =1;j<=3;j++){
						valueMap.put("key"+j, infolist.get(j*i-1).get("KEY_CN"));
						valueMap.put("value"+j, infolist.get(j*i-1).get("VALUE"));
					}
					infoMap.add(valueMap);
				}
				result.setStatus(0);
				result.setMsg("redis监控指标信息获取成功");
				result.setData(infoMap);
				return result;
			}else{
				result.setMsg("没有找到指标信息");
			}
		}else{
			result.setMsg("没有找到该redis的基本信息");
		}
		
		}else{
			result.setMsg("该redis不存在");
		}
		return result;
	}
	@Override
	public MonitoringResult<RedisItem> createExcel(HttpServletResponse response) {
		//用于传递数据结果的方法
		MonitoringResult<RedisItem> result = new MonitoringResult<RedisItem>();
						
		//用于存放RedisItem对象的集合
		List<RedisItem> redisList = new ArrayList<RedisItem>();
		
		String fileName = "环境监控-redis监控表";

		//在数据库全部对象表中查找host类型的数据
		Map<String, String> map = new HashMap<>();
		map.put("objType", "redis");
		List<ObjectManagement> objList = objDao.selectObjName(map);
		if(!objList.isEmpty()){
			for(ObjectManagement obj:objList){
				Map<String, String> objmap = new HashMap<>();
				objmap.put("objId", obj.getObjId());
				objmap.put("itemName", "basic");
				ObjItem objitem = objDao.selectObjItemByItemName(objmap);
				if(objitem!=null){
					List<Map<String, String>> proList = objDao.selectValue(objitem.getItemId());
					RedisItem redisItem = new RedisItem();
					if(!proList.isEmpty()){
						for (Map<String, String> item:proList) {
							if(item.get("KEY").equals("ip")){
								redisItem.setRedisIP(item.get("VALUE"));
							}else if(item.get("KEY").equals("rltip")){
								redisItem.setRedisPrin(item.get("VALUE"));
							}else if(item.get("KEY").equals("links")){
								redisItem.setConnectCount(StringUtils.strToInteger(item.get("VALUE")));
							}else if(item.get("KEY").equals("linkuse")){
								redisItem.setConUseage(item.get("VALUE"));
							}else if(item.get("KEY").equals("allocmem")){
								redisItem.setUseMem(StringUtils.strToInteger(item.get("VALUE")));
							}else if(item.get("KEY").equals("mempiece")){
								redisItem.setMemUseage(item.get("VALUE"));
							}
						}
					}else{
						LOGGER.info("没有该redis的指标信息");
					}
					
					redisItem.setRedisName(obj.getObjName());
					redisItem.setRedisId(obj.getObjId());
					redisItem.setAlarmCount(objDao.getAllWarnCount(objmap));
					AlarmReceiveUser user = objDao.getAlarmReceiveUser(objmap);
					if(user!=null){
						redisItem.setPripacal(user.getReceiveUser());
						redisItem.setPhone(user.getPhone());
						redisItem.setEmail(user.getEmail());
					}
					redisList.add(redisItem);
					result.setMsg("查询redis信息成功");
					result.setStatus(0);
				}else{
					LOGGER.info("没有该redis的基本信息");
				}
			}
		}else{
			LOGGER.info("没有redis类型的对象数据");
		}
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, redisList).getWorkbook();
		  
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		     		
		//对数据结果进行包装传送
		OutputStream fOut = null;    
	        try {
	        	response.reset();
	            fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
	            response.setContentType("application/x-msdownload");    
	            response.setHeader("Content-Disposition", "attachment; filename="+fileName+sdf.format(new Date())+".xls");    
	            fOut = response.getOutputStream();
	            wb.write(fOut); 
	            result.setStatus(0);
	    		result.setMsg("表格导出成功");
	        } catch (Exception e) {    
	            e.printStackTrace(); 
	            
	            result.setStatus(1);
	    		result.setMsg("表格导出失败");
	        } finally {      
	            try {
	            	fOut.flush();
	            	fOut.close();      
	            } catch (IOException e) {      
	                e.printStackTrace();    
	            }      
	        } 
	        
	    return result;
	}
	
	

}
